package com.baibei.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.util.AttributeSet;

/**
 * 带删除的编辑框
 * Created by ChenRui on 2017/5/5 0005 9:54.
 */
public class RaeEditText extends AppCompatEditText {


    public RaeEditText(Context context) {
        this(context, null);
    }

    public RaeEditText(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.editTextStyle);
    }

    public RaeEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    protected void init() {
        if (getInputType() == (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL)) {
            setFilters(new InputFilter[]{new DecimalInputFilter()});
        }

    }

    private class DecimalInputFilter implements InputFilter {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
//            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            // 限制最后一个输入的小数点保留两位小数位
            if (splitArray.length > 1 && dest.length() == dend) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - 2;
                if (diff > 0) {
                    return "";
                }
            }
            return null;
        }
    }
}
